package com.chatdating.service;


import com.chatdating.entity.dto.ContactDto;
import com.chatdating.entity.pojo.Result;
import com.chatdating.entity.vo.LoginInVo;
import com.chatdating.mapper.UserMapper;
import com.chatdating.redis.RedisComponet;
import com.chatdating.utils.EmptyUtil;
import com.chatdating.utils.JwtUtil;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class AuthService {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisComponet redisComponet;

    @Autowired
    private UserMapper userMapper;

    @Transactional
    public String authenticate(String username) {

        // 生成JWT Token
        String s = jwtUtil.generateToken(username);
        //查询该用户联系人  会话 id 联系人名称  最后一条消息 时间 联系人头像
        List<ContactDto> contactDtos1 = userMapper.querySessionByName(username);
        redisComponet.cleanUserContact(username);  //再缓存中清空联系人
        //并且添加缓存缓存
        if (EmptyUtil.isNotEmpty(contactDtos1)) {                         //如果数组不为空 则将联系人添加到redis中
            redisComponet.addUserContactBatch(username, contactDtos1);
        }
        LoginInVo loginInVo = new LoginInVo();
        loginInVo.setTocken(s);
        loginInVo.setUsername(username);
        redisComponet.saveTokenUserInfoDto(loginInVo);
        return s;
    }
    public Result authenticatet(String username,String password) {
        // 生成JWT Token
        String s = jwtUtil.generateToken(username);
        Result success = Result.success(s);
        return success;
    }
    /**
     * 验证Token是否有效
     */
    public boolean verifyToken(String token) {
        return jwtUtil.validateToken(token);
    }

    /**
     * 从Token中获取用户名
     */
    public String getUsernameFromToken(String token) {
        return jwtUtil.getUsernameFromToken(token);
    }
}
